///新版本 我的
import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/app/NewLogin/LoginViewModel.dart';
import 'package:flutter_ahj_app/app/NewMine/SureYouView.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/pluglin/login/LoginUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/zjTopBar.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

import '../../../base/basewidget/view/BaseWidget.dart';

const double space = 15;

class LoginPageView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return loginPageViewState();
  }
}

class loginPageViewState extends BaseState<LoginViewModel, LoginPageView> {
  String showMiMa = "1";
  String loginType = "0"; //0：账号密码登录 1：验证码登录
  String pwd = "", userName = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero, () {
      userName = UserInfoUtils.getUserName();
      _phoneController.text = userName;
      pwd = UserInfoUtils.getUserPassword();
      setState(() {});
    });
  }

  @override
  Widget initWidget() {
    // TODO: implement initWidget
    return Container(
      decoration: BoxDecoration(
          color: Color(0x00f6f7f8),
          image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "img/login_sy_bg.png",
              ))),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Color(0x00f6f7f8),
        appBar: ZJTopBar(
          backgroundColor: Color(0x00f6f7f8),
          elevation: 0,
        ).create(),
        body: _bodyView(),
      ),
    );
  }

  _bodyView() {
    return Column(
      children: [
        _topView(),
        Expanded(
          child: Container(
            margin: EdgeInsets.only(top: 28),
            height: ScreenUtil.getScreenH(context),
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  blurRadius: 16, //阴影范围
                  spreadRadius: 1, //阴影浓度
                  color: Color(0x10479DE4), //阴影颜色
                ),
              ],
              borderRadius: new BorderRadius.all(Radius.circular(16.0)),
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [SQColor.white, SQColor.white]),
            ),
            child: Column(
              children: [
                _loginView(),
                _remeberView(),
                _loginBtnContent(),
                _loginTypeView(),
              ],
            ),
          ),
        ),
        _userAgreexy()
      ],
    );
  }

  bool check = true;
  _remeberView() {
    return Container(
      margin: EdgeInsets.only(left: 12, top: 12,),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
        Row(children: [InkWell(
          onTap: () {
            setState(() {
              this.check = !this.check;
            });
          },
          child: Image.asset(
            this.check ? "img/xieyi_xz.png" : "img/xieyi_wxz.png",
            width: Dimens.dimens20,
            height: Dimens.dimens20,
          ),
        ),
          SizedBox(width: Dimens.dimens10,),
          JText('记住密码'),],),
          GestureDetector(
            child: Text(
              "忘记密码",
              style: TextStyle(
                  fontSize: Dimens.textSize28, color: Color(0xffbfbfbf)),
            ),
            onTap: () => _toForgetPW(),
          ),
        ],
      ),
      padding: EdgeInsets.only(left: 12, right: Dimens.dimens30),
    );
  }

  // 跳转忘记密码界面
  _toForgetPW() {
    Navigator.pushNamed(context, "/WjpswdView");
  }

  _topView() {
    return Container(
      margin: EdgeInsets.only(top: Dimens.dimens20, left: Dimens.dimens22),
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(
                'img/login_logo_small.png',
                height: Dimens.dimens72,
                width: Dimens.dimens72,
                fit: BoxFit.cover,
              )
            ],
          ),
          SizedBox(
            height: Dimens.dimens12,
          ),
          Container(
            padding: EdgeInsets.only(left: Dimens.dimens12),
            child: Row(
              children: [
                JText(
                  '您好，',
                  color: SQColor.black_333333,
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                )
              ],
            ),
          ),
          SizedBox(
            height: Dimens.dimens4,
          ),
          Container(
            padding: EdgeInsets.only(left: Dimens.dimens12),
            child: Row(
              children: [
                JText(
                  '欢迎使用‘青柠’',
                  color: SQColor.black_333333,
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  _loginTypeView() {
    return Container(
      margin: EdgeInsets.fromLTRB(30, 26, 30, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          InkWell(
            child: Container(
              alignment: Alignment.center,
              child: Text(
                "${loginType == "0" ? "短信验证码登录" : "密码登录"}",
                style: new TextStyle(
                    color: Color(0xFF3264F5),
                    fontSize: 13,
                    fontWeight: FontWeight.w400),
              ),
            ),
            onTap: () {
              setState(() {
                if (loginType == "0") {
                  loginType = "1";
                } else {
                  loginType = "0";
                }
              });
            },
          ),
          Container(
            height: 18,
            width: 1,
            color: SQColor.lineE7E7E7,
          ),
          InkWell(
            child: Container(
              child: Text(
                "本机号码一键登录",
                style: new TextStyle(
                    color: Color(0xFF3264F5),
                    fontSize: 13,
                    fontWeight: FontWeight.w400),
              ),
            ),
            onTap: () async {
              if (!_isCheckXY) {
                return ToastUtils.showToast('请先阅读相关协议');
              }
              final connectivityResult =
                  await (Connectivity().checkConnectivity());
              if (connectivityResult == ConnectivityResult.none) {
                return ToastUtils.showToast("请检查手机网络设置");
              }
              loginType == "0" ? _ucLogin() : _ucLogin();
            },
          ),
        ],
      ),
    );
  }

  _loginView() {
    return loginType == "0" ? _umLoginView() : _ucLoginView();
  }

  _umLoginView() {
    TextField name = new TextField(
      autofocus: true,
      decoration: new InputDecoration(
        labelText: "手机号",
        labelStyle: new TextStyle(
            color: SQColor.black_333333,
            fontSize: 16,
            fontWeight: FontWeight.w500),
        hintText: "请输入您的手机号",
        hintStyle: new TextStyle(
            color: Color(0xffbfbfbf),
            fontSize: 14,
            fontWeight: FontWeight.w400),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: SQColor.lineE7E7E7, //边线颜色为黄色
            width: 1, //边线宽度为2
          ),
        ),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(
          color: SQColor.lineE7E7E7, //边框颜色为绿色
          width: 1, //宽度为5
        )),
      ),
      controller: TextEditingController.fromValue(TextEditingValue(
          text: userName, //判断keyword是否为空
          // 保持光标在最后
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream, offset: userName.length)))),
      style: new TextStyle(color: SQColor.black_333333),
      cursorColor: SQColor.black_333333,
      inputFormatters: [
        LengthLimitingTextInputFormatter(11),
        FilteringTextInputFormatter.allow(RegExp("[0-9]")),
      ],
      onChanged: (String str) {
        setState(() {
          userName = str;
          _phoneController.text = str;
        });
      },
    );
    TextField password = new TextField(
      inputFormatters: [
        // WhitelistingTextInputFormatter(RegExp("[0-9]|[a-z]|[A-Z]")),
      ],
      decoration: InputDecoration(
        labelText: "密码",
        labelStyle: new TextStyle(
            color: SQColor.black_333333,
            fontSize: 16,
            fontWeight: FontWeight.w500),
        hintText: "请输入密码",
        hintStyle: new TextStyle(
            color: Color(0xffbfbfbf),
            fontSize: 14,
            fontWeight: FontWeight.w400),
        suffixIcon: new IconButton(
            icon: Icon(
              showMiMa == "1" ? Icons.visibility_off : Icons.visibility,
              color: SQColor.lineE7E7E7,
            ),
            onPressed: isShowMiMa),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: SQColor.lineE7E7E7, //边线颜色为黄色
            width: 1, //边线宽度为2
          ),
        ),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(
          color: SQColor.lineE7E7E7, //边框颜色为绿色
          width: 1, //宽度为5
        )),
      ),
      obscureText: showMiMa == "1" ? true : false,
      controller: TextEditingController.fromValue(
        TextEditingValue(
            text: pwd,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: pwd.length))),
      ),
      style: new TextStyle(color: SQColor.black_333333),
      cursorColor: SQColor.black_333333,
      onChanged: (String str) {
        setState(() {
          pwd = str;
        });
      },
    );
    return Container(
      margin: EdgeInsets.only(
          left: Dimens.dimens26, right: Dimens.dimens26, top: Dimens.dimens20),
      child: Column(
        children: <Widget>[
          name,
          SizedBox(
            height: Dimens.dimens18,
          ),
          password,
        ],
      ),
    );
  }

  TextEditingController _phoneController = new TextEditingController(text: ''),
      _checkController = new TextEditingController(text: '');
  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器
  _ucLoginView() {
    TextField _tfPhone = TextField(
        decoration: InputDecoration(
          labelText: "手机号",
          labelStyle: new TextStyle(
              color: SQColor.black_333333,
              fontSize: 16,
              fontWeight: FontWeight.w500),
          hintText: "请输入您的手机号",
          hintStyle: new TextStyle(
              color: Color(0xffbfbfbf),
              fontSize: 14,
              fontWeight: FontWeight.w400),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: SQColor.lineE7E7E7, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: SQColor.lineE7E7E7, //边框颜色为绿色
            width: 1, //宽度为5
          )),
        ),
        controller: _phoneController,
        style: TextStyle(color: SQColor.black_333333),
        cursorColor: SQColor.black_333333,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    GestureDetector _rbGetCheck = GestureDetector(
      child: new Container(
        alignment: Alignment.center,
        height: Dimens.dimens36,
        width: Dimens.dimens96,
        child: Text(
          _checkText,
          style: new TextStyle(
              fontSize: Dimens.textSize28,
              color: _checkText == "获取验证码"
                  ? SQColor.black_333333
                  : SQColor.per60Black),
        ),
      ),
      onTap: _checkText == "获取验证码" ? () => _getCheckCode() : null,
    );

    TextField _tfCheck = TextField(
        decoration: InputDecoration(
          labelText: "验证码",
          labelStyle: new TextStyle(
              color: SQColor.black_333333,
              fontSize: 16,
              fontWeight: FontWeight.w500),
          hintText: "请输入验证码",
          hintStyle: new TextStyle(
              color: Color(0xffbfbfbf),
              fontSize: 14,
              fontWeight: FontWeight.w400),
          suffixIcon: _rbGetCheck,
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: SQColor.lineE7E7E7, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
            color: SQColor.lineE7E7E7, //边框颜色为绿色
            width: 1, //宽度为5
          )),
        ),
        controller: _checkController,
        style: TextStyle(color: SQColor.black_333333),
        cursorColor: SQColor.black_333333,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(6),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    return Container(
      padding: EdgeInsets.fromLTRB(26, 20, 26, 0),
      child: Column(
        children: <Widget>[
          _tfPhone,
          SizedBox(
            height: Dimens.dimens18,
          ),
          _tfCheck,
        ],
      ),
    );
  }

  _getCheckCode() async {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    if (_phoneController.text == null || _phoneController.text.trim() == "") {
      ToastUtils.showToast("请输入手机号");
      return;
    }
    bool matched = exp.hasMatch(_phoneController.text);
    if (!matched) {
      ToastUtils.showToast("请输入正确格式的手机号");
      return;
    }
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      ToastUtils.showToast("请检查手机网络设置");
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });
    viewModel.getCheckCode(_phoneController.text);
    Stream stream = viewModel.getCheckCodeStream();
    stream.listen((baseData) {
      if (baseData != null && baseData['code'] == "0") {
        ToastUtils.showToast(baseData['data']);
      } else if (baseData != null && baseData['code'] == "1") {
        ToastUtils.showToast(baseData['data']);
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      } else {
        ToastUtils.showToast("验证码获取失败");
        setState(() {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        });
      }
    });
  }

  void isShowMiMa() {
    setState(() {
      showMiMa == "1" ? showMiMa = "0" : showMiMa = "1";
    });
  }

  _loginBtnContent() {
    return InkWell(
      child: Container(
        margin: EdgeInsets.fromLTRB(27, 35, 27, 0),
        decoration: BoxDecoration(
          color: SQColor.theme_color,
          borderRadius: BorderRadius.all(Radius.circular(24.0)),
        ),
        child: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              JText(
                '登录',
                color: SQColor.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              )
            ],
          ),
        ),
        height: 48,
      ),
      onTap: () async {
        FocusScope.of(context).requestFocus(FocusNode());
        final connectivityResult = await (Connectivity().checkConnectivity());
        if (connectivityResult == ConnectivityResult.none) {
          return ToastUtils.showToast("请检查手机网络设置");
        }
        RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
        if (!_isCheckXY) {
          ToastUtils.showToast("请先同意用户隐私协议");
          return;
        }
        if (loginType == '0') {
          if (userName == null || userName == "") {
            ToastUtils.showToast("请输入手机号");
            return;
          }
          bool matched = exp.hasMatch(userName);
          if (!matched) {
            ToastUtils.showToast("请输入正确格式的手机号");
            return;
          }

          _passWordLogin();
        } else {
          if (_phoneController.text == null ||
              _phoneController.text.trim() == "") {
            ToastUtils.showToast("请输入手机号");
            return;
          }
          bool matched = exp.hasMatch(_phoneController.text);
          if (!matched) {
            ToastUtils.showToast("请输入正确格式的手机号");
            return;
          }
          _codeLogin();
        }
      },
    );
  }

  _codeLogin() async {
    if (_checkController.text == null || _checkController.text.trim() == "") {
      ToastUtils.showToast("请输入验证码");
      return;
    }
    ToastUtils.showLoading();
    viewModel.checkCodeLogin(_phoneController.text, _checkController.text);
    Stream<Map> stream = viewModel.getCheckCodeLoginStream();
    stream.listen((userBeanEntity) {
      ToastUtils.dissLoading();
      _checkLoginResult(userBeanEntity, 'code');
    });
  }

  // 密码登录
  _passWordLogin() async {
    ToastUtils.showLoading();
    setState(() {});
    viewModel.setlogInData(userName, pwd);
    Stream<Map> sss = viewModel.getDataStream();
    sss.listen((userBeanEntity) {
      ToastUtils.dissLoading();
      _checkLoginResult(userBeanEntity, 'password');
    });
  }

  _checkLoginResult(Map userBeanEntity, String type) async {
    if (userBeanEntity != null && userBeanEntity['code'] == '0') {
      if (check) {
        UserInfoUtils.setUserPassword(pwd);
        UserInfoUtils.setUserName(userName);
      } else {
        UserInfoUtils.setUserPassword("");
        UserInfoUtils.setUserName("");
      }

      UserInfoUtils.setUserToken(userBeanEntity['data']['accessToken']);
      print(UserInfoUtils.getUserToken());
      Navigator.pushNamedAndRemoveUntil(
        context,
        "/home",
        (check) => false,
      );
    } else if (userBeanEntity != null && userBeanEntity['code'] == '1') {
      ToastUtils.showToast(userBeanEntity['msg']);
    } else {
      final connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        ToastUtils.showToast("请检查手机网络设置");
      } else {
        if (type == 'code') {
          ToastUtils.showToast("验证码错误");
        } else if (type == 'password') {
          // ToastUtils.showToast("账号密码错误");
        } else {
          ToastUtils.showToast("一键登录失败");
        }
      }
    }
  }

  bool _isCheckXY = false;
  _userAgreexy() {
    return Container(
      color: SQColor.white,
      alignment: Alignment.center,
      padding: EdgeInsets.only(bottom: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              setState(() {
                _isCheckXY = !_isCheckXY;
              });
            },
            child: Image.asset(
              _isCheckXY ? "img/xieyi_xz.png" : "img/xieyi_wxz.png",
              width: Dimens.dimens20,
              height: Dimens.dimens20,
            ),
          ),
          RichText(
            maxLines: 2,
            text: TextSpan(
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  setState(() {
                    _isCheckXY = !_isCheckXY;
                  });
                },
              text: '  本人已阅读、知晓并同意',
              style: TextStyle(
                color: SQColor.black_999999,
                fontSize: Dimens.dimens12,
              ),
              children: <TextSpan>[
                TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Navigator.pushNamed(context, "/WebViewUntil", arguments: {
                        "title": '用户协议',
                        "url":
                            'https://ahj-static.oss-cn-beijing.aliyuncs.com/html/index.html'
                      });
                    },
                  text: '《用户隐私协议》',
                  style: TextStyle(
                      color: SQColor.black_333333,
                      fontSize: Dimens.dimens12,
                      fontWeight: FontWeight.bold),
                ),
                // TextSpan(
                //   text: '和',
                //   style: TextStyle(
                //       color: SQColor.white,
                //       fontSize: Dimens.dimens14),
                // ),
                // TextSpan(
                //   text: '《自雇者承揽协议》',
                //   recognizer: TapGestureRecognizer()
                //     ..onTap = () {
                //       Navigator.pushNamed(context, "/PTXYView",
                //           arguments: '2');
                //     },
                //   style: TextStyle(
                //       color: SQColor.secondary1,
                //       fontSize: Dimens.dimens14,
                //       fontWeight: FontWeight.bold),
                // ),
              ],
            ),
          )
        ],
      ),
    );
  }

  _ucLogin() async {
//    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
//    if (_phoneController.text == null || _phoneController.text.trim() == "") {
//      ToastUtils.showToast("请输入手机号");
//      return;
//    }
//    bool matched = exp.hasMatch(_phoneController.text);
//    if (!matched) {
//      ToastUtils.showToast("请输入正确格式的手机号");
//      return;
//    }
//    if (_checkController.text == null || _checkController.text.trim() == "") {
//      ToastUtils.showToast("请输入验证码");
//      return;
//    }

    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      return ToastUtils.showToast("请检查手机网络设置");
    }

    var data12 = await LoginUtils.YijianDengluZhibo();

    if (data12 == "-100") {
      //切换到其他方式登录
      Navigator.pushNamed(context, "/LoginPageView");
      return;
    } else if (data12 == "1") {
      return;
    }

    print(data12);

    setState(() {});
    viewModel.yiJianLogin(data12);
    Stream<Map> stream = viewModel.yiJianLoginStream();
    stream.listen((userBeanEntity) {
      _checkLoginResult(userBeanEntity, 'yijian');
    });
  }

  // _checkUCLoginResult(UserBeanEntity userBeanEntity) async {
  //   if (userBeanEntity != null && userBeanEntity.code == 0) {
  //     UserInfoUtils.setUserToken(userBeanEntity.accessToken);
  //     print(UserInfoUtils.getUserToken());
  //
  //     viewModel.changeRoles();
  //     Stream stream = viewModel.getRoleStream();
  //     stream.listen((result) {
  //       if (result == null || result["code"] != 0) {
  //         UserInfoUtils.setUserToken("");
  //         ToastUtils.showToast("登录失败");
  //         isLogIng = "0";
  //         setState(() {});
  //       } else {
  //         saveUserData(userBeanEntity);
  //       }
  //     });
  //   } else if (userBeanEntity != null && userBeanEntity.code == 1) {
  //     ToastUtils.showToast(userBeanEntity.message);
  //     isLogIng = "0";
  //     setState(() {});
  //   } else {
  //     ToastUtils.showToast("账号密码错误");
  //     isLogIng = "0";
  //     setState(() {});
  //   }
  // }
  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
    countDownTimer = null;
  }
}
